from rest_framework import serializers
from .models import AnalysisTask, DataSource, AnalysisResult, Report
from data_crawler.models import CrawledData
import logging

logger = logging.getLogger(__name__)

class DataSourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = DataSource
        fields = ('id', 'name', 'type', 'credentials', 'is_active', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')
        extra_kwargs = {
            'credentials': {'write_only': True}
        }

class AnalysisResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = AnalysisResult
        fields = ('id', 'title', 'description', 'data', 'visualization_type', 'created_at')
        read_only_fields = ('id', 'created_at')

class AnalysisTaskSerializer(serializers.ModelSerializer):
    results = AnalysisResultSerializer(many=True, read_only=True, source='analysis_results')
    
    class Meta:
        model = AnalysisTask
        fields = ('id', 'name', 'type', 'status', 'progress', 'parameters', 
                 'result', 'error_message', 'created_at', 'updated_at', 
                 'completed_at', 'results')
        read_only_fields = ('id', 'status', 'progress', 'result', 'error_message',
                          'created_at', 'updated_at', 'completed_at')

class TaskCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = AnalysisTask
        fields = ('name', 'type', 'parameters')

class TaskUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = AnalysisTask
        fields = ('status', 'progress', 'result', 'error_message', 'completed_at')
        read_only_fields = ('completed_at',)

class ReportSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    data_source_name = serializers.CharField(source='data_source.name', read_only=True)
    metrics = serializers.ListField(child=serializers.CharField(), required=True)
    
    class Meta:
        model = Report
        fields = [
            'id', 'name', 'type', 'user', 'data_source', 'data_source_name',
            'metrics', 'parameters', 'result', 'status', 'error_message',
            'start_date', 'end_date', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'status', 'error_message', 'result', 'created_at', 'updated_at']
    
    def validate_metrics(self, value):
        """验证 metrics 字段"""
        logger.info(f"Validating metrics: {value}")
        valid_metrics = ['data_volume', 'engagement', 'user_activity', 'content_analysis', 'sentiment']
        
        if not isinstance(value, list):
            raise serializers.ValidationError("metrics must be a list")
        
        if not value:
            raise serializers.ValidationError("At least one metric must be selected")
        
        invalid_metrics = [m for m in value if m not in valid_metrics]
        if invalid_metrics:
            raise serializers.ValidationError(f"Invalid metrics: {invalid_metrics}")
        
        return value
    
    def validate(self, data):
        """验证整个数据"""
        logger.info(f"Validating report data: {data}")
        
        # 验证日期范围
        if data['start_date'] > data['end_date']:
            raise serializers.ValidationError("End date must be after start date")
        
        return data 